package com.yingxin.yx.framework.wx;

import com.alibaba.fastjson.JSON;
import com.yingxin.yx.framework.commons.helper.OKHttpHelper;

public class WeixinHttpHelper {

    private WeixinHttpHelper() {
    }

    private static String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={secret}&code={code}&grant_type=authorization_code";

    public static String smallAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={code}&grant_type=authorization_code";

    private static String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}&lang=zh_CN";

    private static String liveInfoAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={secret}";

    /**
     * 获取用户openId
     *
     * @return
     */
    public static String getSmallOpenId(String appId, String secret, String code) {
        WeixinAccessToken accessToken = getSmallAccessToken(appId, secret, code);
        return accessToken.getOpenId();
    }

    /**
     * 获取微信AccessToken信息
     */
    public static WeixinAccessToken getSmallAccessToken(String appId, String secret, String code) {
        final String url = smallAccessTokenUrl.replace("{appId}", appId).replace("{secret}", secret).replace("{code}", code);
        String json = OKHttpHelper.get(url);
        WeixinAccessToken accessToken = JSON.parseObject(json, WeixinAccessToken.class);
        return accessToken;
    }

    /**
     * 获取微信直播小程序AccessToken信息
     */
    public static WeixinAccessToken getLiveInfoAccessToken(String appId, String secret) {
        final String url = liveInfoAccessTokenUrl.replace("{appId}", appId).replace("{secret}", secret);
        String json = OKHttpHelper.get(url);
        WeixinAccessToken accessToken = JSON.parseObject(json, WeixinAccessToken.class);
        return accessToken;
    }

    /**
     * 获取用户openId
     *
     * @return
     */
    public static String getOpenId(String appId, String secret, String code) {
        WeixinAccessToken accessToken = getAccessToken(appId, secret, code);
        return accessToken.getOpenId();
    }

    /**
     * 获取微信AccessToken信息
     */
    public static WeixinAccessToken getAccessToken(String appId, String secret, String code) {
        final String url = accessTokenUrl.replace("{appId}", appId).replace("{secret}", secret).replace("{code}", code);
        String json = OKHttpHelper.get(url);
        WeixinAccessToken accessToken = JSON.parseObject(json, WeixinAccessToken.class);
        return accessToken;
    }


    /**
     * 获取微信用户基本信息
     */
    public static String getUserInfo(String openId, String accessToken) {
        final String url = userInfoUrl.replace("{openId}", openId).replace("{accessToken}", accessToken);
        String json = OKHttpHelper.get(url);
        return json;
    }

}
